export default {
  //声明一个方法  用于登录成功后修改用户数据
  loginOK(state, params) {
    const {
      newname,
      userid
    } = params
    state.islogin = true; //修改state 中islogin的属性值  //底层调用 this.$store.commit('loginOK')
    state.username = newname;
    state.userid = userid;
  },
  //退出登录
  logoff(state) {
    state.islogin = false;
    state.username = '';
    state.userid = '';
    state.car = [];
    state.totalMount = 0;
    state.totalPrice = 0;
  },
  addToCar(state, goodsinfo) {
    //点击加入购物车 把商品信息保存到store中的car上
    //1.如果购物车之中,之前就已经有这个商品了,那么就只需要更新数量即可
    //2.如果没有,则直接把商品数据,push到car中即可

    //默认 在购物车中没有找到对应的商品
    var flag = false
    //
    // console.log(state.car)
    state.car.some(item => {
      if (item.id == goodsinfo.id) {
        item.count += parseInt(goodsinfo.count)
        // item.price += parseInt(goodsinfo.price)
        // item.count +=1
        flag = true
        return true
      }
    })

    //如果最终循环完毕,得到的flag还是false 则把商品数据直接push进购物车
    if (!flag) {
      state.car.unshift(goodsinfo)
    }
    // console.log(state.car)

    //当更新car之后,把car数组存储到localStorage中
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  //减少商品数量
  reduceGood(state, id) { //第二个参数为商品id
    var len = state.car.length;
    for (var i = 0; i < len; i++) {
      if (state.car[i].id == id) {
        state.car[i].count--;
        if (state.car[i].count == 0) {
          state.car.splice(i, 1);
          break;
        }
      }
    }
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  //增加商品数量
  addGood(state, id) { //第二个参数为商品id
    var len = state.car.length;
    for (var i = 0; i < len; i++) {
      if (state.car[i].id == id) {
        state.car[i].count++;
      }
    }
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  //删除某个商品
  removeGood(state, params) {
    const {
      id,
      price,
      mount
    } = params
    let len = state.car.length;
    for (var i = 0; i < len; i++) {
      if (state.car[i].id == id) {
        state.car.splice(i, 1);
        state.totalPrice -= price * 100 * mount;
        state.totalMount -= mount;
        break;
      }
    }
    localStorage.setItem('totalPrice', JSON.stringify(state.totalPrice))
    localStorage.setItem('totalMount', JSON.stringify(state.totalMount))
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  //获取商品总的(总数量、总价格)
  SET_TOTAL(state, params) {
    const {
      price,
      type
    } = params;
    switch (type) {
      case 'PLUS':
        state.totalPrice += price * 100;
        state.totalMount += 1;
        break;
      case 'MINUS':
        state.totalPrice -= price * 100;
        state.totalMount -= 1;
        break;
      default:
        break;
    }
    localStorage.setItem('totalPrice', JSON.stringify(state.totalPrice));
    localStorage.setItem('totalMount', JSON.stringify(state.totalMount));
  },
  //取消全选时  即没有商品选中时
  deselect_all(state) {

  }
}